<template>
  <div style=" margin-top: 100px;text-align: center">微信扫码登录中，请稍候...</div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/admin";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { HOME_URL } from "@/config";
import { ElMessage } from "element-plus";
import { wxLoginApi } from "@/api/modules/login";

const router = useRouter();
const userStore = useUserStore();

onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get("code");
  if (!code) {
    ElMessage.error("获取微信 code 失败");
    return;
  }

  try {
    const res = await wxLoginApi({ code });
    userStore.setToken(res.data.token);
    userStore.setUserId(res.data.id);
    await initDynamicRouter();
    router.push(HOME_URL);
  } catch (err) {
    console.error(err);
    ElMessage.error("微信登录失败");
  }
});
</script>
